package com.itheima.myreflect3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @program: Myset
 * @description: 获取构造方法对象并创建对象
 * @author: xuejingjing
 * @create: 2021-06-27 22:04
 **/
public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // method1();
        //1,获取class对象
        Class aClass = Class.forName("com.itheima.myreflect3.Student");
        //2，获取私有的构造方法对象
        Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
        //报错了
        //被private修饰的成员，不能直接使用的。
        //如果用反射强制获取并使用，需要临时取消访问检查
        declaredConstructor.setAccessible(true);
        /**
         * 3，利用newInstance 创建Student的对象，并会调用这个类的构造方法（私有的）
         * private...name的值为:lisi
         * private...student...有参构造方法
         */
        Student student = (Student) declaredConstructor.newInstance("lisi");

        System.out.println("2:" + student);
        /*2:Student{name='null', age=0}*/
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //1,获取class对象
        Class aClass = Class.forName("com.itheima.myreflect3.Student");

        //2,获取构造方法对象
        Constructor constructor = aClass.getConstructor(String.class, int.class);

        //3,利用newInstance 创建Student的对象
        Student student = (Student) constructor.newInstance("zhangsan", 18);
        System.out.println("1:" + student);
    }
}